package com.server.service;

import com.server.dal.DatabaseHelper;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @Author e4glet
 * 2025年3月5日
 * */

// 核心功能模块
public class OICQServer {
    private static final int PORT = 12345;
    private ServerSocket serverSocket;
    private ExecutorService executorService;
    // 存储在线用户信息，键为用户ID，值为Socket对象
    private ConcurrentHashMap<Integer, Socket> onlineUsers = new ConcurrentHashMap<>();

    // 构造函数中初始化serverSocket和executorService
    public OICQServer() {
        try {
            serverSocket = new ServerSocket(PORT);
            executorService = Executors.newCachedThreadPool();
            System.out.println("服务器启动，端口号：" + PORT);

            // 添加关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("服务器正在关闭...");
                try {
                    DatabaseHelper.updateAllUsersOffline();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                System.out.println("所有用户已设置为离线状态");
            }));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 启动服务器
    public void start() {
        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                executorService.execute(new ClientHandler(clientSocket, onlineUsers));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
